# -*- coding: utf-8 -*-
import os
import yaml
import os
from log import log
from pydantic import BaseModel, computed_field
import secrets


def compute_val(v):
    return eval(v)


class DbModel(BaseModel):
    type: str
    server: str
    username: str
    password: str
    database: str


class Minio(BaseModel):
    minio_url: str
    access_key: str
    secret_key: str
    file_limit: str

    @computed_field
    @property
    def file_limit_size(self) -> int:
        return eval(self.file_limit) if '*' in self.file_limit else self.file_limit


class Redis(BaseModel):
    host:  str
    password: str


class CfgMode(BaseModel):
    db: DbModel
    minio: Minio
    redis: Redis
    app: str
    SECRET: str
    ACCESS_TOKEN_EXPIRE_RULE: str
    allow_origins: list

    @computed_field
    @property
    def SECRET_KEY(self) -> str:
        return eval(self.SECRET) if 'secret' in self.SECRET else self.SECRET

    @computed_field
    @property
    def ACCESS_TOKEN_EXPIRE_MINUTES(self) -> int:
        return eval(self.ACCESS_TOKEN_EXPIRE_RULE) if '*' in self.ACCESS_TOKEN_EXPIRE_RULE else self.ACCESS_TOKEN_EXPIRE_RULE


class CFG:
    env = 'dev'
    __obj = None
    __init_flag = True

    # 一次实例
    def __new__(cls, *args, **kwargs):
        if cls.__obj is None:
            cls.__obj = object.__new__(cls)
        return cls.__obj

    # 一次初始化
    def __init__(self):
        if self.__init_flag:
            if os.getenv("ENV"):
                self.env = os.getenv("ENV")
            with open("config/config.yaml", 'r', encoding='utf-8') as yml_file:
                cfg = yaml.load(yml_file, Loader=yaml.SafeLoader)
            log.info(self.env)
            # setattr 加的属性没有属性提示
            # cfg = CfgMode(**cfg[self.env], **cfg['common']).model_dump()
            # for k, v in cfg.items():
            #     setattr(self, k, v)
            cfg = CfgMode(**cfg[self.env], **cfg['common'])
            log.info(cfg)
            self.cfg = cfg
            self.__init_flag = False

